package com.cangshi.controller;

import com.alibaba.fastjson.JSONObject;
import com.cangshi.entity.User;
import com.cangshi.exception.JsonException;
import com.cangshi.service.UserService;
import com.cangshi.shiro.ssesion.OnlineSessionManager;
import com.cangshi.utils.MD5Tools;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.json.JsonObject;
import javax.servlet.http.HttpServletRequest;

/**
 * Created by Eoly on 2017/6/5.
 */
@Controller
@RequestMapping("/user")
public class UserActionController {

    @Autowired
    private
    UserService userService;

    @Autowired
    private
    OnlineSessionManager onlineSessionManager;

    /**
     * 用户登录逻辑
     *
     * @param username
     * @param password
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/login", method = RequestMethod.POST, produces = "application/json;charset=utf-8")
    public String login(
            @RequestParam(required = false) String username,
            @RequestParam(required = false) String password
    ) {

        JSONObject jsonObject = new JSONObject();

        Subject subject = SecurityUtils.getSubject();

        password = MD5Tools.MD5(password);

        UsernamePasswordToken token = new UsernamePasswordToken(username, password);

        try {
            //登录，即身份验证
            subject.login(token);
            onlineSessionManager.addOnlineSession(subject.getSession().getId());
            User user = userService.getUserByLoginName(token.getUsername());
            // 在session中存放用户信息
            subject.getSession().setAttribute("userLogin", user);
            jsonObject.put("error", 0);
            jsonObject.put("msg", "登录成功");
            // 返回sessionId作为token
            jsonObject.put("token",subject.getSession().getId());
        } catch (IncorrectCredentialsException e) {
            throw new JsonException("用户名或密码错误", 405);
        } catch (LockedAccountException e) {
            throw new JsonException("登录失败，该用户已被冻结", 405);
        } catch (AuthenticationException e) {
            throw new JsonException("用户名或密码错误", 405);
        }
        return jsonObject.toString();
    }

    /**
     * 用户注销逻辑
     *
     * @return
     */
    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public String logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "redirect:/user/login.html";
    }

    /**
     * 用户注册逻辑跳转到添加用户
     *
     * @return
     */
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public String register() {
        return "forward:/users";
    }

    @RequiresPermissions("user:admin")
    @ResponseBody
    @RequestMapping(value = "/letout/{id}", method = RequestMethod.POST, produces = "application/json;charset=utf-8")
    public String letout(
            @PathVariable String id
    ) {
        JSONObject jsonObject = new JSONObject();
        if (onlineSessionManager.getSession(id) == null) {
            throw new JsonException("下线失败，该用户已下线", 450);
        }
        onlineSessionManager.letoutSession(id);
        jsonObject.put("error", 0);
        jsonObject.put("msg", "下线成功");
        return jsonObject.toString();
    }
}
